//
//  WJ_StartSportVC.m
//  ChatOnLine
//
//  Created by dllo on 16/8/11.
//  Copyright © 2016年 WWT. All rights reserved.
//
// BUG 画线与定位不一样?????????
#import "WJ_StartSportVC.h"
#import "UIBarButtonItem+NavicationBar.h"
#import <ActionSheetPicker.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreMotion/CoreMotion.h>
#import <MapKit/MapKit.h>
#import "WJDataManager.h"
#define kBaseColor [UIColor colorWithRed:90 / 255.0 green:177 / 255.0 blue:64 / 255.0 alpha:1]
#define kLatitudeDelta 0.002703
#define kLongitudeDelta 0.0017

@interface WJ_StartSportVC ()<UINavigationControllerDelegate,MKMapViewDelegate>
 /** 地图 */
@property (nonatomic, strong) MKMapView *mapView;
 /** 定位管理器 */
@property (nonatomic, strong) CLLocationManager *manager;
 /**运动位置数组*/
@property (nonatomic, strong) NSMutableArray* locations;
 /** 运动的距离 */
@property (nonatomic, assign) CGFloat distance;
 /** 显示跑步的距离*/
@property (nonatomic, strong) UILabel *kmLable;
 /** 显示时间 */
@property (nonatomic, strong) UILabel *timeLable;
 /** 显示速度 */
@property (nonatomic, strong) UILabel *speedLable;
 /** 开始按钮 */
@property (nonatomic, strong) UIButton *stopBut;
 /** 继续按钮 */
@property (nonatomic, strong) UIButton *continueBut;
 /** 结束按钮 */
@property (nonatomic, strong) UIButton *endBut;
 /** 定时器 */
@property (nonatomic, strong) NSTimer *timer;
 /** 运动时间*/
@property (nonatomic, assign) NSInteger seconds;
 /** 计步器IOS8出现 */
@property (nonatomic, strong) CMPedometer *pedometer;
 /** 记录走的距离 */
@property (nonatomic, assign) CGFloat presentLength;
@end

@implementation WJ_StartSportVC

/** 第二个页面也要签协议 */
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.delegate=self;
    // 接受通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(numberOfStepsChanged:) name:@"distance" object:nil];
}
// 移除通知
-(void)viewWillDisappear:(BOOL)animated{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"distance" object:nil];
    
}

 /** 页面出现开始倒计时 */
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self countDown:3];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self config];
}

- (void)config
{
    self.view.backgroundColor = kBaseColor;
    
    self.navigationController.navigationBarHidden = YES;
    
    // 1. 创建计步器
    self.pedometer = [[CMPedometer alloc]init];
    
}

-(void)countDown:(int)count{
    if(count <=0){
        //倒计时已到，作需要作的事吧。
        [UIView animateWithDuration:0.2 animations:^{
            self.view.backgroundColor = [UIColor whiteColor];
        }];
        
        [self crateView];
        
        return;
    }
    UILabel *lblCountDown = [[UILabel alloc]init];
    [self.view addSubview:lblCountDown];
    [lblCountDown mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(200, 200));
    }];
    lblCountDown.textColor = [UIColor whiteColor];
    lblCountDown.font = [UIFont boldSystemFontOfSize:200];
    lblCountDown.backgroundColor = [UIColor clearColor];
    lblCountDown.textAlignment = 1;
    lblCountDown.text = [NSString stringWithFormat:@"%d",count];
    [UIView animateWithDuration:1
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         lblCountDown.alpha =0;
                         lblCountDown.transform =CGAffineTransformScale(CGAffineTransformIdentity,0.5, 0.5);
                     }
                     completion:^(BOOL finished) {
                         [lblCountDown removeFromSuperview];
                         //递归调用，直到计时为零
                         [self countDown:count -1];
                     }
     ];
}


- (void)crateView
{
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 3 / 9)];
    self.mapView.delegate = self;
    // 跟踪用户的位置 会多次调用方法
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    [self.view addSubview:self.mapView];
    
    /** 给地图上添加一个Button 让用户点击的时候回到用户的地方 */
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.mapView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(- 10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [button setImage:[UIImage imageNamed:@"Location.png"] forState:0];
    [button addTarget:self action:@selector(LocationAction:) forControlEvents:1<<6];
    
    
    self.kmLable = [[UILabel alloc]init];
    [self.view addSubview:self.kmLable];
    [self.kmLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(SCREEN_HEIGHT * 3 / 9 + 20);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(100);
    }];
    self.kmLable.font = [UIFont fontWithName:@"Knockout-HTF67-FullBantamwt" size:120];
    self.kmLable.textAlignment = 1;
    self.kmLable.text = @"0.00";
    self.kmLable.textColor = [UIColor blackColor];
    
    UILabel *lable = [[UILabel alloc]init];
    [self.view addSubview:lable];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.kmLable).offset(100);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    lable.text = @"距离(公里)";
    lable.textAlignment = 1;
    lable.textColor = [UIColor grayColor];
    
    
    self.timeLable = [[UILabel alloc]init];
    [self.view addSubview:self.timeLable];
    [self.timeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(SCREEN_HEIGHT * 3 / 9 + 170);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(- SCREEN_WIDTH / 2);
        make.height.mas_equalTo(50);
    }];
    self.timeLable.font = [UIFont fontWithName:@"Knockout-HTF67-FullBantamwt" size:50];
    self.timeLable.textAlignment = 1;
    self.timeLable.text = @"00:00:00";
    self.timeLable.textColor = [UIColor blackColor];
    
    UILabel *secTime = [[UILabel alloc]init];
    [self.view addSubview:secTime];
    [secTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.timeLable).offset(50);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(- SCREEN_WIDTH / 2);
        make.height.mas_equalTo(30);
    }];
    secTime.text = @"时长";
    secTime.textAlignment = 1;
    secTime.textColor = [UIColor grayColor];
    
    
    self.speedLable = [[UILabel alloc]init];
    [self.view addSubview:self.speedLable];
    [self.speedLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(SCREEN_HEIGHT * 3 / 9 + 170);
        make.left.mas_equalTo(SCREEN_WIDTH / 2);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    self.speedLable.font = [UIFont fontWithName:@"Knockout-HTF67-FullBantamwt" size:50];
    self.speedLable.textAlignment = 1;
    self.speedLable.text = @"0.00";
    self.speedLable.textColor = [UIColor blackColor];
    
    UILabel *countLab = [[UILabel alloc]init];
    [self.view addSubview:countLab];
    [countLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.speedLable).offset(50);
        make.left.mas_equalTo(SCREEN_WIDTH / 2);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(30);
    }];
    countLab.text = @"平均速度(公里/时)";
    countLab.textAlignment = 1;
    countLab.textColor = [UIColor grayColor];
    
    
    self.stopBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.stopBut];
    [self.stopBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(SCREEN_WIDTH/2 - 45);
        make.bottom.mas_equalTo(-0.07 * SCREEN_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(90, 90));

    }];
    [self.stopBut setImage:[UIImage imageNamed:@"Stop"] forState:0];
    [self.stopBut addTarget:self action:@selector(stopAct:) forControlEvents:1<<6];
    
    
    self.continueBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.continueBut.hidden = YES;
    [self.view addSubview:self.continueBut];
    [self.continueBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(SCREEN_WIDTH/2 - 15 - 90);
        make.bottom.mas_equalTo(-0.07 * SCREEN_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(90, 90));
    }];
    [self.continueBut setImage:[UIImage imageNamed:@"Continue"] forState:0];
    [self.continueBut addTarget:self action:@selector(continueAct:) forControlEvents:1<<6];

    self.endBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.endBut.hidden = YES;
    [self.view addSubview:self.endBut];
    [self.endBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.continueBut).offset(120);
        make.bottom.mas_equalTo(-0.07 * SCREEN_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(90, 90));
        
    }];
    self.endBut.backgroundColor = kBaseColor;
    self.endBut.layer.cornerRadius = 45;
    [self.endBut setTitle:@"结束" forState:0];
    [self.endBut addTarget:self action:@selector(endAct:) forControlEvents:1<<6];
    
    /** 开始计步 */
    [self gotoOpenStepCountFunction];
    
}

/** 暂停按钮 */
- (void)stopAct:(UIButton *)but
{
    self.stopBut.hidden = YES;
    self.continueBut.hidden = NO;
    self.endBut.hidden = NO;
    
    [self.timer invalidate];
    
    /** 结束计算距离 */
    [self gotoCloseStepCountFunction];
}


/** 继续按钮 */
- (void)continueAct:(UIButton *)but
{
    self.stopBut.hidden = NO;
    self.continueBut.hidden = YES;
    self.endBut.hidden = YES;
    
    /** 开始计算距离 */
    [self gotoOpenStepCountFunction];
}


#pragma mark - 将数据存储到数据库 结束按钮
- (void)endAct:(UIButton *)but
{
    /** 结束计算距离 */
    [self gotoCloseStepCountFunction];
    
    /** 跑步的距离 */
    if (self.presentLength > 100  || self.distance > 100 ) {
        
        // 获取时间戳
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString * dateStr = [formatter stringFromDate:[NSDate date]];
        
        
        // 将开始跑步的时间  跑步的距离  跑步的 用时记录数据库
        if ([CMPedometer isStepCountingAvailable]) {
            
            [[WJDataManager shareFMDB]insertWithTime:dateStr Diatance:[NSString stringWithFormat:@"%f", self.presentLength / 1000.0] UseTime:[NSString stringWithFormat:@"%f",self.seconds / 3600.0]];
            
        }else{
            
            [[WJDataManager shareFMDB]insertWithTime:dateStr Diatance:[NSString stringWithFormat:@"%f", self.distance / 1000.0] UseTime:[NSString stringWithFormat:@"%f",self.seconds / 3600.0]];
        }
        
        // 将图片写入本地
        UIImage *image = [self imageWithUIView:self.mapView];
        BOOL result = [self saveImage:image WithName:dateStr];
        if (result) {
            NSLog(@"地图截屏成功");
        }

        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"此次运动距离太短无法保存,是否结束本次运动?" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"结束运动" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:action];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:^{}];
        
    }
}






- (void)levelTimer:(NSTimer *)time
{
    _seconds++;
    
    self.timeLable.text = [self withTime:[NSString stringWithFormat:@"%ld",(long)_seconds]];
}

- (NSString *)withTime:(NSString *)time
{
    // 秒
    NSInteger sec = time.integerValue % 60;
    // 分
    NSInteger min = time.integerValue / 60;
    // 小时
    NSInteger hour = time.integerValue / 3600;
    
    return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hour,min,sec];
}





/** 开始计步器 */
-(void)gotoOpenStepCountFunction
{
    
    // 开始定位
    [self.manager startUpdatingLocation];
    
    //启动定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    
    if ([CMPedometer isStepCountingAvailable]) { // 开始计步
        
        // 计步器得到的距离
        [_pedometer startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            
            if (error) {
                NSLog(@"error====%@",error);
                
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"startStepCount"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
            }else {
                NSLog(@"BBB步数====%@",pedometerData.numberOfSteps);
                NSLog(@"BBB距离====%@",pedometerData.distance);
                
                self.presentLength = self.presentLength + pedometerData.distance.floatValue;
                
                NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f", self.presentLength],@"distance", nil];
                
                // 发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"distance" object:nil userInfo:dic];
                
            }
            
        }];
        
    }
}


// 通知的方法
-(void)numberOfStepsChanged:(NSNotification *)notif
{
    NSString *distance = [[notif userInfo] objectForKey:@"distance"];
    
    NSLog(@"***********   ********** 走了多远  %@   *************",distance);
    dispatch_async(dispatch_get_main_queue(), ^{
        
        /** 走的总长度 */
        CGFloat length =  distance.integerValue / 1000.0;
        /** 走的总时间 */
        CGFloat time = self.seconds / 3600.0;
        /** 速度 */
        CGFloat speed = length / time;
        
        if (distance) {
            
            self.speedLable.text = [NSString stringWithFormat:@"%.2f",speed];
            self.kmLable.text = [NSString stringWithFormat:@"%.2f",length];
            
        }
        
    });
}


- (void)gotoCloseStepCountFunction
{
    /** 关闭计步器 */
    if ([CMPedometer isStepCountingAvailable]) {
        
        [_pedometer stopPedometerUpdates];
        
    }else{
        
        //  结束定位
        [self.manager stopUpdatingLocation];
    }
}


-(NSMutableArray *)locations{
    if (!_locations) {
        _locations = [NSMutableArray array];
    }
    return _locations;
}



/***************** 定位功能 真正的定位*********************/
//用户位置发生改变时触发
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    // userLocation 大头针模型 用于描述一个大头针
    // 取出用户的位置
    CLLocationCoordinate2D coordination = userLocation.location.coordinate;
    
    NSLog(@"%f,%f",coordination.latitude,coordination.longitude);
    
    // 设置MapView显示的属性 进来的时候是在中间
    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    // 设置显示区域
    MKCoordinateSpan span = MKCoordinateSpanMake(kLatitudeDelta, kLongitudeDelta);
    MKCoordinateRegion region = MKCoordinateRegionMake(coordination,span);
    [mapView setRegion:region animated:YES];
    
    if (self.locations.count > 0) {
        
        if (![CMPedometer isStepCountingAvailable]) {
            _distance += [userLocation.location distanceFromLocation:self.locations.lastObject];
        }
        
        // 画线
        // 这块必须动态分派内存，具体为什么，还不知道。用malloc分配内存在堆内分配内存，用完改变量后，必须手动释放内存。
        CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * 2);
        coords[0] = ((CLLocation *)self.locations.lastObject).coordinate;
        coords[1] = userLocation.location.coordinate;
        [self.mapView addOverlay:[MKPolyline polylineWithCoordinates:coords count:2]];
        free(coords);
        
    }
    [self.locations addObject:userLocation.location];
    
    
    // 跑步距离的算法
    if (![CMPedometer isStepCountingAvailable]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            /** 走的总长度 */
            CGFloat length =  _distance / 1000.0;
            
            /** 走的总时间 */
            CGFloat time = self.seconds / 3600.0;
            
            /** 速度 */
            CGFloat speed = length / time;
            
            if (_distance) {
                
                self.speedLable.text = [NSString stringWithFormat:@"%.2f",speed];
                
                self.kmLable.text = [NSString stringWithFormat:@"%.2f",length];
            }
        });
    }
    
}

#pragma mark - MKMapViewDelegate  画线 调用MKMapView代理方法进行覆盖物加载
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay {
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolyline *polyLine = (MKPolyline *)overlay;
        MKPolylineRenderer *aRenderer = [[MKPolylineRenderer alloc] initWithPolyline:polyLine];
        aRenderer.strokeColor = [UIColor blueColor];
        aRenderer.fillColor = [UIColor blueColor];
        aRenderer.lineWidth = 3;
        return aRenderer;
    }
    return nil;
}

// 点击回到自己的位置
- (void)LocationAction:(UIButton *)but
{
    MKCoordinateSpan span = MKCoordinateSpanMake(kLatitudeDelta, kLongitudeDelta);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.mapView.userLocation.location.coordinate ,span);
    [self.mapView setRegion:region animated:YES];
}



/** 懒加载 */
- (CLLocationManager *)manager
{
    if (_manager == nil) {
        
        _manager = [[CLLocationManager alloc]init];
        
        // 3. 位置间隔之后重新定位
        _manager.distanceFilter = kCLDistanceFilterNone;
        
        // 4. 定位的精确度
        _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
        // 必须设置的
        [_manager requestAlwaysAuthorization];//始终授权
        [_manager requestWhenInUseAuthorization];// 使用时授权
        
        //设置允许后台定位参数，保持不会被系统挂起
        [_manager setPausesLocationUpdatesAutomatically:NO];
        
    }
    return _manager;
}



#pragma mark - 截屏代码
- (UIImage *)imageWithUIView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


- (BOOL)saveImage:(UIImage*)image WithName:(NSString*)imageName
{
    NSString *imagePath = [kRunMap stringByAppendingPathComponent:imageName];
    BOOL isCreated = [UIImagePNGRepresentation(image) writeToFile:imagePath options:NSAtomicWrite error:nil];
    return isCreated;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
